package cn.silky.demo.web.controller;

import cn.silky.demo.web.entity.SysAccount;
import cn.silky.demo.web.repository.SysAccountRepository;
import cn.silky.demo.web.service.ISysAccountService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * <p>
 * 账号表 前端控制器
 * </p>
 *
 * @author ListJiang
 * @since 2021-11-01
 */
@Log4j2
@RequiredArgsConstructor
@RestController
@RequestMapping("/sys-account")
public class SysAccountController {
    private final ISysAccountService iSysAccountService;
    private final SysAccountRepository sysAccountRepository;
    private final PasswordEncoder passwordEncoder;

    @GetMapping(value = "/", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    Flux<SysAccount> all() {
        if (log.isDebugEnabled())
            log.debug("用户全量查询");
        return sysAccountRepository.findAll();
    }

    @GetMapping(value = "/{id}")
    Mono<SysAccount> findById(@PathVariable Long id) {
        return iSysAccountService.findById(id);
    }

    @PostMapping(value = "/{id}")
    Mono<SysAccount> postById(@PathVariable Long id, @RequestBody SysAccount sysAccount) {
        return sysAccountRepository.existsById(id).flatMap(t -> {
            if (t) {
                return sysAccountRepository.save(sysAccount.setId(id));
            } else {
                return sysAccountRepository.save(sysAccount);
            }
        });
    }

    @PutMapping(value = "/{id}")
    Mono<SysAccount> putById(@PathVariable Long id, @RequestBody SysAccount sysAccount) {
        return sysAccountRepository.save(sysAccount.setId(id).setPassword(passwordEncoder.encode(sysAccount.getPassword())));
    }

    @PutMapping(value = "/reset-password/{id}")
    Mono<SysAccount> resetPasswordById(@PathVariable Long id) {
        return sysAccountRepository.findById(id)
                .map(sysAccount -> sysAccount.setPassword(passwordEncoder.encode("123")))
                .flatMap(sysAccount -> sysAccountRepository.save(sysAccount));
    }

    @DeleteMapping(value = "/{id}")
    Mono<Void> deleteById(@PathVariable Long id) {
        return sysAccountRepository.deleteById(id);
    }

    @GetMapping("/find-by-account")
    Mono<SysAccount> findAllByAccount(@RequestParam(value = "account", required = false) String account) {
        return iSysAccountService.findByAccount(account);
    }

    @GetMapping("/find-by-email")
    Mono<SysAccount> findAllByEmail(@RequestParam(value = "email", required = false) String email) {
        return iSysAccountService.findByEmail(email);
    }
}